package com.lingyi.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingyi.common.config.WechatConfig;
import com.lingyi.common.core.domain.WechatUserResponse;
import com.lingyi.common.utils.RestTemplateUtil;
import com.lingyi.framework.web.service.WechatService;
import com.lingyi.system.domain.PublicUser;
import com.lingyi.system.service.IPublicUserService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @PackageName: com.lingyi.handler
 * @ClassName: TaskHandler
 * @Description:
 * @Author: czl
 * @Date: 2025/4/19 16:50
 */
@RequiredArgsConstructor
@Component("taskRunHandler")
public class TaskRunHandler {

    private static Logger logger = LoggerFactory.getLogger(TaskRunHandler.class);

    private final IPublicUserService publicUserService;
    private final WechatConfig wechatConfig;
    private final RestTemplateUtil restTemplateUtil;
    private final WechatService wechatService;

    public void taskRunHandler() {
        publicUserService.truncationTable();
        String accessToken = wechatService.getAccessToken();
        List<String> allOpenIds = getAllOpenIds(accessToken);
        boolean flag = savePublicUser(allOpenIds);
        logger.info("关注公众号用户同步状态：{}",flag);
    }

    public boolean savePublicUser(List<String> openIds) {
        if (openIds.isEmpty()) {
            // 没有需要保存的用户
            return true;
        }

        Set<String> openIdSet = new HashSet<>(openIds);

        LambdaQueryWrapper<PublicUser> queryWrapper = Wrappers.lambdaQuery(PublicUser.class);
        queryWrapper.in(PublicUser::getOpenId, openIdSet);
        List<PublicUser> existingUsers = publicUserService.list(queryWrapper);

        for (PublicUser user : existingUsers) {
            openIdSet.remove(user.getOpenId());
        }

        List<PublicUser> newPublicUsers = new ArrayList<>();
        for (String openId : openIdSet) {
            PublicUser publicUser = new PublicUser();
            publicUser.setOpenId(openId);
            newPublicUsers.add(publicUser);
        }

        return publicUserService.saveBatch(newPublicUsers, 1000);
    }

    public List<String> getAllOpenIds(String accessToken) {
        List<String> allOpenIds = new ArrayList<>();
        String nextOpenId = "";
        while (nextOpenId != null) {
            String url = String.format(wechatConfig.getPublicUserUrl(), accessToken, nextOpenId);

            ResponseEntity<String> response = restTemplateUtil.sendGetRequest(url);

            if (response == null || response.getBody() == null) {
                break;
            }

            WechatUserResponse wechatUserResponse = parseResponse(response.getBody());

            if (wechatUserResponse != null && wechatUserResponse.getData() != null) {
                allOpenIds.addAll(wechatUserResponse.getData().getOpenid());
                nextOpenId = wechatUserResponse.getNext_openid();
            } else {
                // 没有更多数据了
                nextOpenId = null;
            }
        }

        return allOpenIds;
    }

    /**
     * 解析微信返回的JSON响应
     *
     * @param responseBody JSON字符串
     * @return 解析后的WechatUserResponse对象
     */
    private WechatUserResponse parseResponse(String responseBody) {
        // 这里假设你有一个Jackson ObjectMapper实例来进行JSON解析
        // 如果没有，可以创建一个新的ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return objectMapper.readValue(responseBody, WechatUserResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
